package com.line.tools.util;

import com.alibaba.fastjson.JSONObject;
import com.line.config.cons.CodeCons;
import com.line.model.pojo.ErrorResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpUtils {
	private static Logger log = LoggerFactory.getLogger(HttpUtils.class);

	public static void writeErrorResponse(HttpServletResponse response, CodeCons code, String action) throws Exception {
		ErrorResponse codeResponse = new ErrorResponse(code);
		JSONObject object = (JSONObject) JSONObject.toJSON(codeResponse);
		response.setContentType("application/json;charset=utf-8");
		PrintWriter writer = response.getWriter();
		writer.write(object.toJSONString());
		writer.flush();
		writer.close();
	}

	public static void writeResponse(HttpServletRequest request, HttpServletResponse response, CodeCons code) throws Exception {
		ErrorResponse codeResponse = new ErrorResponse(code);
		JSONObject object = (JSONObject) JSONObject.toJSON(codeResponse);
		response.setContentType("application/json;charset=utf-8");
		writeInfo(request, object);
		PrintWriter writer = response.getWriter();
		writer.write(object.toJSONString());
		writer.flush();
		writer.close();
	}

	public static void writeResponse(HttpServletRequest request, HttpServletResponse response, CodeCons code, HttpStatus status) throws Exception {
		response.setStatus(status.value());
		response.setContentType("application/json;charset=utf-8");
		ErrorResponse codeResponse = new ErrorResponse(code);
		JSONObject object = (JSONObject) JSONObject.toJSON(codeResponse);
		writeInfo(request, object);
		PrintWriter writer = response.getWriter();
		writer.write(object.toJSONString());
		writer.flush();
		writer.close();
	}

	public static void writeResponse(HttpServletRequest request, HttpServletResponse response, CodeCons code, Object object) throws Exception {
		response.setContentType("application/json;charset=utf-8");
		ErrorResponse codeResponse = new ErrorResponse(code);
		JSONObject resultJSON = (JSONObject) JSONObject.toJSON(codeResponse);
		writeInfo(request, object);
		PrintWriter writer = response.getWriter();
		writer.write(resultJSON.toJSONString());
		writer.flush();
		writer.close();
	}

	public static String getIpAddress(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	private static void writeInfo(HttpServletRequest request, Object jsonObject) {
		Map<String, String[]> map = request.getParameterMap();
		Object req = null;
		if (map != null) {
			try {
				req = JSONObject.toJSON(map);
			} catch (Exception e) {
				log.error("/aop/request/exception:", e);
			}
		}
	}

	public static boolean matchIp(String sourceIp, String targetIp) {
		// 根据授权类型的不同，走不同的业务处理
		boolean flag = true;
		if (!StringBasicUtils.isBlank(sourceIp)) {
			String[] sourceIps = sourceIp.split(",");
			String targetIps[] = targetIp.split(",");
			for (int i = 0; i < sourceIps.length; i++) {
				String source = sourceIps[i];
				for (int j = 0; j < targetIps.length; j++) {
					String target = targetIps[j];
					if (source.equals(target)) {
						flag = false;
					}
				}
			}
		} else {
			return false;
		}
		return flag;
	}

	public static String requestHttpGet(String path) throws Exception {
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");// 设定请求的方法为"POST"，默认是GET
		conn.setDoInput(true);// 设置是否从httpUrlConnection读入，默认情况下是true;
		conn.setAllowUserInteraction(false);
		conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
		conn.setConnectTimeout(10 * 1000);
		// 设置Header头
		ByteArrayOutputStream outRes = new ByteArrayOutputStream();
		InputStream in = conn.getInputStream();
		int b;
		while ((b = in.read()) != -1) {
			outRes.write(b);
		}
		outRes.flush();
		byte resByte[] = outRes.toByteArray();
		outRes.close();
		conn.disconnect();
		return new String(resByte, "UTF-8");
	}

	public static HttpResponse doGet(String host, String path, String method, Map<String, String> headers, Map<String, String> querys) throws Exception {
		HttpClient httpClient = wrapClient(host);

		HttpGet request = new HttpGet(buildUrl(host, path, querys));
		for (Map.Entry<String, String> e : headers.entrySet()) {
			request.addHeader(e.getKey(), e.getValue());
		}

		return httpClient.execute(request);
	}

	public static HttpResponse doPost(String host, String path, String method, Map<String, String> headers, Map<String, String> querys,
			Map<String, String> bodys) throws Exception {
		HttpClient httpClient = wrapClient(host);

		HttpPost request = new HttpPost(buildUrl(host, path, querys));
		for (Map.Entry<String, String> e : headers.entrySet()) {
			request.addHeader(e.getKey(), e.getValue());
		}

		if (bodys != null) {
			List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();

			for (String key : bodys.keySet()) {
				nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
			}
			UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
			formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
			request.setEntity(formEntity);
		}

		return httpClient.execute(request);
	}

	public static HttpResponse doPost(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, String body)
			throws Exception {
		HttpClient httpClient = wrapClient(host);

		HttpPost request = new HttpPost(buildUrl(host, path, querys));
		for (Map.Entry<String, String> e : headers.entrySet()) {
			request.addHeader(e.getKey(), e.getValue());
		}

		if (StringUtils.isNotBlank(body)) {
			request.setEntity(new StringEntity(body, "utf-8"));
		}

		return httpClient.execute(request);
	}

	public static HttpResponse doPost(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, byte[] body)
			throws Exception {
		HttpClient httpClient = wrapClient(host);

		HttpPost request = new HttpPost(buildUrl(host, path, querys));
		for (Map.Entry<String, String> e : headers.entrySet()) {
			request.addHeader(e.getKey(), e.getValue());
		}

		if (body != null) {
			request.setEntity(new ByteArrayEntity(body));
		}

		return httpClient.execute(request);
	}

	public static HttpResponse doPut(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, String body)
			throws Exception {
		HttpClient httpClient = wrapClient(host);

		HttpPut request = new HttpPut(buildUrl(host, path, querys));
		for (Map.Entry<String, String> e : headers.entrySet()) {
			request.addHeader(e.getKey(), e.getValue());
		}

		if (StringUtils.isNotBlank(body)) {
			request.setEntity(new StringEntity(body, "utf-8"));
		}

		return httpClient.execute(request);
	}

	public static HttpResponse doPut(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, byte[] body)
			throws Exception {
		HttpClient httpClient = wrapClient(host);

		HttpPut request = new HttpPut(buildUrl(host, path, querys));
		for (Map.Entry<String, String> e : headers.entrySet()) {
			request.addHeader(e.getKey(), e.getValue());
		}

		if (body != null) {
			request.setEntity(new ByteArrayEntity(body));
		}

		return httpClient.execute(request);
	}

	public static HttpResponse doDelete(String host, String path, String method, Map<String, String> headers, Map<String, String> querys) throws Exception {
		HttpClient httpClient = wrapClient(host);

		HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
		for (Map.Entry<String, String> e : headers.entrySet()) {
			request.addHeader(e.getKey(), e.getValue());
		}

		return httpClient.execute(request);
	}

	private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
		StringBuilder sbUrl = new StringBuilder();
		sbUrl.append(host);
		if (!StringUtils.isBlank(path)) {
			sbUrl.append(path);
		}
		if (null != querys) {
			StringBuilder sbQuery = new StringBuilder();
			for (Map.Entry<String, String> query : querys.entrySet()) {
				if (0 < sbQuery.length()) {
					sbQuery.append("&");
				}
				if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
					sbQuery.append(query.getValue());
				}
				if (!StringUtils.isBlank(query.getKey())) {
					sbQuery.append(query.getKey());
					if (!StringUtils.isBlank(query.getValue())) {
						sbQuery.append("=");
						sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
					}
				}
			}
			if (0 < sbQuery.length()) {
				sbUrl.append("?").append(sbQuery);
			}
		}
		return sbUrl.toString();
	}

	private static HttpClient wrapClient(String host) {
		HttpClient httpClient = new DefaultHttpClient();
		if (host.startsWith("https://")) {
			sslClient(httpClient);
		}

		return httpClient;
	}

	private static void sslClient(HttpClient httpClient) {
		try {
			SSLContext ctx = SSLContext.getInstance("TLS");
			X509TrustManager tm = new X509TrustManager() {
				public X509Certificate[] getAcceptedIssuers() {
					return null;
				}

				public void checkClientTrusted(X509Certificate[] xcs, String str) {

				}

				public void checkServerTrusted(X509Certificate[] xcs, String str) {

				}
			};
			ctx.init(null, new TrustManager[] { tm }, null);
			SSLSocketFactory ssf = new SSLSocketFactory(ctx);
			ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			ClientConnectionManager ccm = httpClient.getConnectionManager();
			SchemeRegistry registry = ccm.getSchemeRegistry();
			registry.register(new Scheme("https", 443, ssf));
		} catch (KeyManagementException ex) {
			throw new RuntimeException(ex);
		} catch (NoSuchAlgorithmException ex) {
			throw new RuntimeException(ex);
		}
	}
}
